var utils = module.exports;
var fs = require("fs");
var querystring = require('querystring');
var http = require('http');
var jsonData = require("../config/config.json");
var mysqlAccess  = require("./dataAccess.js");
/**
 * Check and invoke callback function
 */
utils.invokeCallback = function(cb) {
    if(!!cb && typeof cb === 'function') {
        cb.apply(null, Array.prototype.slice.call(arguments, 1));
    }
};

utils.inherits = function (a, b) {
    function C () {}
    C.prototype = b.prototype;
    a.prototype = new C;
};

//判断本地文件夹是否存在,不存在则创建一个新的文件夹
utils.folderPathExists = function (filePath){
    if (fs.existsSync(filePath)) {
        console.log('目录已存在!');
    } else {
        fs.mkdirSync(filePath); //创建文件夹
        console.log('目录已创建成功!');
    }
    return filePath;
};

//判断本地文件是否存在,不存在则创建一个新的文件
utils.filePathExists = function (fileName){
    if (fs.existsSync(fileName)) {
        console.log('文件已存在!');
    } else {
        fs.writeFile(fileName,'', function(err){ //创建文件
            if(err) throw err;
            console.log('文件已创建成功!');
        });
    }
    return fileName;
};

//通过文件完整路径获取上一级目录路径
utils.getDirPath = function (filePath){
    var dirPath = '';
    var str = filePath.split('\\');

    for(var i = 0; i < str.length - 1; i++){
        dirPath += str[i] + '/';
    }
    return dirPath;
};

utils.copyFile = function(fileInPath, fileOutPath, cb){
    var fileOutFolderPath = fileOutPath.substr(0, fileOutPath.lastIndexOf('/'));
    if(this.folderPathExists(fileOutFolderPath)){
        console.log('[copy] copy' + fileInPath + ' to ' + fileOutPath);
        var fileReadStream = fs.createReadStream(fileInPath);
        var fileWriteStream = fs.createWriteStream(fileOutPath);
        fileReadStream.pipe(fileWriteStream);

        fileWriteStream.on('close', function(){
            console.log('copy over');
            cb({code:200});
        });
    }
};



//连接到游戏服务端接口
utils.sendToPorcy = function(jsonObj,path,cb){
    var config = require('../config/jsonData');
    //转换为json字符串
    console.log("·······sendToPorcy",jsonObj);

    var hostname = config.proxyServer.hostname;
    var port = config.proxyServer.port;
    var path = path;
    path += "?";
    var data = JSON.stringify(jsonObj);
    for(var i in  jsonObj){
        console.log("jsonObj[i]",jsonObj[i]);
        path += i+ "=" + jsonObj[i] + "&"

    }

    path=path.substring(0,path.length-1);
    var options = {
        hostname:hostname,
        port:port,
        path:path,
        method:'GET',
        headers: {
            'Content-Type':'application/x-www-form-urlencoded'
        }
    };

    console.log("--------sendToPorcy",options);
    console.log("--------data",data);


    var req = http.request(options, function(response){
        var str = '';
        response.on('data', function(data_info){
            str = str + data_info;
        });
        response.on('end', function(info){
            str = JSON.parse(str);
            console.log("3333333",str);
            if(str.code == 0){
                cb({code:200});
            }else{
                cb(null,str);
            }
        });
    });

    req.write(data);
    req.end();
    req.on('error', function(e){
        console.log('problem with request:' + e.message);
        if(e.message.match('connect ECONNREFUSED')){
            console.log('服务器响应: ' + e.message + ' (请查看:'+hostname+':'+port+' 服务器是否已启动?)');
            return cb(null,{code:500, msg: '没有可用的服务器,请查看后台数据服务器是否已启动?'});
        }else
            cb(null,{code:500, msg:'未知错误!',info:e});
    });
};


//连接数据库
utils.connectToMysql = function(obj,cb){
    mysqlAccess.runSqlInfo(obj,cb);
};
